($ => {
    $.fn.formPopup = function (options) {
        return new Promise((resolve, reject) => {
            options = options || {};
            const $form = $(this[0]);
            const $popup = $('<div />');
            $(document.body).append($popup);
            const popup = $popup
                .dxPopup({
                    title: 'Form',
                    showTitle: true,
                    visible: true,
                    maxWidth: 600,
                    maxHeight: 300,
                    toolbarItems: [
                        {
                            location: 'after',
                            toolbar: 'bottom',
                            widget: 'dxButton',
                            options: {
                                text: '确定',
                                onClick: () => {
                                    const formInstance = $form.dxForm('instance');
                                    if (formInstance) {
                                        const validationResult = formInstance.validate();
                                        if (validationResult.isValid) {
                                            if (options.callback instanceof Function) {
                                                options.callback(formInstance.option('formData'), () => popup.hide());
                                            } else {
                                                resolve(formInstance.option('formData'));
                                                popup.hide();
                                            }
                                        }
                                    }
                                },
                            },
                        },
                        {
                            location: 'after',
                            toolbar: 'bottom',
                            widget: 'dxButton',
                            options: {
                                text: '取消',
                                onClick: () => {
                                    popup.hide();
                                },
                            },
                        },
                    ],
                    contentTemplate: () => {
                        return $form;
                    },
                    onHidden: e => {
                        e.component.dispose();
                        $(e.element).remove();
                    },
                    ...options,
                })
                .dxPopup('instance');
        });
    };
})(jQuery);